package com.lyh.controller;


import com.lyh.pojo.User;
import com.lyh.service.user.UserService;
import com.lyh.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    public UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/index/login")
    @ResponseBody
    public void Login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 获取login页面的表单数据：userCode，userPassword
        String userCode = request.getParameter("userCode");
        String userPassword = request.getParameter("userPassword");

        if (userCode == null || userPassword == null) {
            // 如果验证未通过 给前端返回一个error信息
            request.setAttribute("error","用户名或者密码不正确");
            response.sendRedirect("/login.jsp");
            //请求转发到 login页面，并显示 error 信息
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
        // 把表单的数据 放进 工具map里
        Map<String, String> map = new HashMap<>();
        map.put("userCode",userCode);
        map.put("userPassword",userPassword);

        // 使用工具map，完成业务操作

        User user = userService.checkLogin(map);

        if (user != null ) {
            // 如果验证通过，往session中存放{"userSession":user}
            request.getSession().setAttribute(Constants.USER_SESSION,user);
            //请求转发到 frame页面
            request.getRequestDispatcher("/WEB-INF/jsp/frame.jsp").forward(request,response);

        } else {

            // 如果验证未通过 给前端返回一个error信息
            request.setAttribute("error","用户名或者密码不正确");
            response.sendRedirect("/login.jsp");
            //请求转发到 login页面，并显示 error 信息
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }

    }

}
